package controllers;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Pesanan;
import models.User;
import system.Controller;
import system.MailServer;

/**
 * Kelola Pesanan Controller
 * 
 * @author Rezan Achmad
 */
@WebServlet(name = "KelolaPesananController", urlPatterns = {"/kelolaPesanan/tiba", "/kelolaPesanan/dibayar", "/kelolaPesanan/dikonfirmasi", "/kelolaPesanan/baru", "/kelolaPesanan/cancel", "/kelolaPesanan/view"})
public class KelolaPesananController extends Controller {

    @Override
    protected void initRules() {
        // Pegawai
        boolean pegawai = !identity.isUser() && !identity.isGuest();
        rules.put("/kelolaPesanan/tiba", pegawai);
        rules.put("/kelolaPesanan/dibayar", pegawai);
        rules.put("/kelolaPesanan/dikonfirmasi", pegawai);
        rules.put("/kelolaPesanan/baru", pegawai);
        rules.put("/kelolaPesanan/cancel", pegawai);
        rules.put("/kelolaPesanan/view", pegawai);
        
    }

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userPath = request.getServletPath();

        // Get process POST Request
        if (isPost) {
            setStatusRequest(request, response);
            return;
        }

        // Set serveltPath
        request.setAttribute("servletPath", userPath);

        if (userPath.equals("/kelolaPesanan/tiba")) {
            actionTiba(request, response);
        } else if (userPath.equals("/kelolaPesanan/dibayar")) {
            actionDibayar(request, response);
        } else if (userPath.equals("/kelolaPesanan/dikonfirmasi")) {
            actionDikonfirmasi(request, response);
        } else if (userPath.equals("/kelolaPesanan/baru")) {
            actionBaru(request, response);
        } else if (userPath.equals("/kelolaPesanan/cancel")) {
            actionCancel(request, response);
        } else if (userPath.equals("/kelolaPesanan/view")) {
            actionView(request, response);
        }
    }

    private void setStatusRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get paramater
        String pesananId = request.getParameter("pesanan_id");
        String status = request.getParameter("status");

        // Check parameter
        if (pesananId != null && !pesananId.isEmpty() && status != null && !status.isEmpty()) {
            // Parse status
            int intStatus = Integer.parseInt(status);

            // Check status
            if (Pesanan.isStatusValid(intStatus) && intStatus != Pesanan.STATUS_INCART) {
                // Parses pesanan id
                int intPesananId = Integer.parseInt(pesananId);

                // Get Pesanan
                Pesanan pesanan = Pesanan.getInstance().get(intPesananId);
                pesanan.status = intStatus;

                // Update
                boolean success = pesanan.update();
                
                // Kirim Email
                if(success && (pesanan.status == Pesanan.STATUS_PAY)) {
                    sendEmailPay(pesanan);
                }
            }
        }
        
        response.sendRedirect(request.getContextPath() + request.getServletPath());
    }

    private void actionTiba(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get dan set list pesanan
        request.setAttribute("pesanans", Pesanan.getInstance().getAllByStatus(Pesanan.STATUS_ARRIVED));

        // Set View
        setView("/kelolaPesanan/index", request, response);
    }

    private void actionDibayar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get dan set list pesanan
        request.setAttribute("pesanans", Pesanan.getInstance().getAllByStatus(Pesanan.STATUS_PAY));

        // Set View
        setView("/kelolaPesanan/index", request, response);
    }

    private void actionDikonfirmasi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get dan set list pesanan
        request.setAttribute("pesanans", Pesanan.getInstance().getAllByStatus(Pesanan.STATUS_CONFIRM_PAY));

        // Set View
        setView("/kelolaPesanan/index", request, response);
    }

    private void actionBaru(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get dan set list pesanan
        request.setAttribute("pesanans", Pesanan.getInstance().getAllByStatus(Pesanan.STATUS_NEW));

        // Set View
        setView("/kelolaPesanan/index", request, response);
    }

    private void actionCancel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get parameter
        String id = request.getParameter("id");
        
        // Cek id
        if(id!=null && !id.isEmpty()) {
            // Parse id
            int intId = Integer.parseInt(id);
            
            // Get Pesanan and delete
            Pesanan pesanan = Pesanan.getInstance().get(intId);
            if(pesanan.delete()) {
                sendEmailCancel(pesanan);
            }
        }
        
        response.sendRedirect(request.getContextPath()+"/kelolaPesanan/baru");
    }
    
    private void actionView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get parameter
        String id = request.getParameter("id");
        
        // Cek id
        if(id!=null && !id.isEmpty()) {
            // Parse id
            int intId = Integer.parseInt(id);
            
            // Get Pesanan and delete
            Pesanan pesanan = Pesanan.getInstance().get(intId);
            
            request.setAttribute("pesanan", pesanan);
            // Set View
            setView("/kelolaPesanan/view", request, response);
        }
        else
        {
        response.sendRedirect(request.getContextPath()+"/kelolaPesanan/baru");
        }
    }

    /**
     * Mengirim email ke pengguna jika pesanan dibatalkan.
     * @param pesanan
     */
    private void sendEmailCancel(Pesanan pesanan) {
        StringBuilder subject = new StringBuilder();
        StringBuilder message = new StringBuilder();
        User user = pesanan.getUser();
        
        // Isi email
        subject.append("Pembatalan Pesanan ID ").append(pesanan.id);
        message.append("Hai ").append(user.nama_lengkap).append(",\n\n");
        message.append("Pesanan Anda dengan ID ").append(pesanan.id).append(" telah kami batalkan karena melawati batas pembayaran atau tidak sesuai dengan kebijakan perusahaan kami.\n");
        message.append("Kami mohon maaf atas ketidaknyamanan ini.");
        
        // Kirim email
        MailServer.sendEmail(user.email, subject.toString(), message.toString());
    }

    /**
     * Mengirim email ke pengguna jika pesanan dinyatakan telah dibayar oleh pegawai.
     * @param pesanan 
     */
    private void sendEmailPay(Pesanan pesanan) {
        StringBuilder subject = new StringBuilder();
        StringBuilder message = new StringBuilder();
        User user = pesanan.getUser();
        
        // Isi email
        subject.append("Pembayaran Pesanan ID ").append(pesanan.id);
        message.append("Hai ").append(user.nama_lengkap).append(",\n\n");
        message.append("Terima kasih atas pembayaran Anda untuk Pesanan ID ").append(pesanan.id).append(".\n");
        message.append("Semoga Anda puas dengan pelayanan kami.");
        
        // Kirim email
        MailServer.sendEmail(user.email, subject.toString(), message.toString());
    }
}
